/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {void} Do not return anything, modify root in-place instead.
 */
var flatten = function(root) {

    if(!root)return;
    if(!root.left&&!root.right)return;

    let res,
        pre,
        p,
        stack = [root];

    while(stack.length>0){
        p = stack[stack.length-1];
        if((!p.left&&!p.right) || (pre&&(pre===p.left||pre===p.right))){
            pre = stack.pop();
            if(!res){
                res = pre;
            }else{
                pre.right = res;
                res = pre;
                res.left = null;
            }
        }else{
            if(p.left)stack.push(p.left);
            if(p.right)stack.push(p.right);
        }
    }
};